package sa4.css
import scala.xml.NodeSeq
import java.io.File
import java.io.PrintWriter
import java.io.BufferedWriter
import java.io.FileWriter

object css {

  def setCss(page: String, obj: String, values: String*) {

    //var path: String = new File("./css").getCanonicalPath + "/"
    var file: String = "./css/" + page
    val writer = new PrintWriter(new BufferedWriter(new FileWriter(file, false)));

    var attributes = " {";
    for (x <- values)
      attributes += x + ";\n"
    attributes += "}\n"

    // search old file  
    try {
      var lines = "";
      var source = scala.io.Source.fromFile("./css/" + page)
      for (line <- source.getLines())
        lines += line
        
      source.close()

      println(lines)

      var split1 = lines.split(obj)(1)
      var split2 = split1.split("}")(0)
      var split3 = split2.substring(1)
      var attrArray: Array[String] = split3.split("\n")

      println(attrArray)

      for (oldAttr <- attrArray)
        for (value <- values)
          if (oldAttr.split(":")(0) == value.split(":")(0))
            attrArray(attrArray.indexOf(oldAttr)) = value
          else
            attrArray.+(value)

      println(attrArray)

      writer.print(obj + attrArray)
      writer.println("")
      writer.close()

    } catch {
      case ioe: Exception => {
        println(ioe)
        writer.print(obj + attributes)
        writer.println("")
        writer.close()
        println("i wrote something")
      }
    }

  }

}